package org.gpf.game.tank.online;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
/**
 * 坦克大战的服务器
 * @author gaopengfei
 * @date 2015-4-26 下午2:32:10
 */
public class TankServer {

	public static final int TCP_PORT = 8888;		// TCP监听端口
	public static final int UDP_PORT = 6666;		// UDP监听端口
	
	private static int id = 100;
	List<Client>clients = new ArrayList<Client>();	// 将客户端保存到一个ArrayList中
	
	/**
	 * 启动服务器
	 */
	public  void start(){
		
		new Thread(new UDPThread()).start(); // 启动UDP线程接收客户端发送的数据报
		
		ServerSocket ss = null;
		try {
			ss= new ServerSocket(TCP_PORT);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		while (true) {
			Socket s = null;
			try {
				s = ss.accept();
				DataInputStream dis = new DataInputStream(s.getInputStream());
				int udpPort = dis.readInt(); 
				String IP = s.getInetAddress().getHostAddress();
				Client c = new Client(IP, udpPort); // 根据客户端IP和udp端口创建客户端
				clients.add(c); // 加入客户端集合
				DataOutputStream dos = new DataOutputStream(s.getOutputStream());
				dos.writeInt(id++); // 给客户端分配唯一的id
				System.out.println("A Client connected,Address = " + s.getInetAddress() + ",TCP端口" + s.getPort() + "，udp端口" + udpPort);
			} catch (IOException e) {
				e.printStackTrace();
			} finally{
				if (s!=null) {
					try {
						s.close();
						s = null;
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	public static void main(String[] args) {

		new TankServer().start();
	}
	
	private class Client{
		
		String IP;
		int udpPort;
		public Client(String iP, int udpPort) {
			super();
			IP = iP;
			this.udpPort = udpPort;
		}
		
	}
	
	private class UDPThread implements Runnable{
		
		byte[] buf = new byte[1024];

		@Override
		public void run() {
			// 接收客户端发送的数据转发给其他客户端
			DatagramSocket ds = null;
			try {
				ds = new DatagramSocket(UDP_PORT);
			} catch (SocketException e) {
				e.printStackTrace();
			}
			System.out.println("服务器的UDP线程启动了，在" + UDP_PORT + "端口监听。");
			while (ds!=null) {
				DatagramPacket dp = new DatagramPacket(buf, buf.length);
				try {
					ds.receive(dp);	// 在拿到数据报之前一直阻塞
					System.out.println("服务器收到了客户端的一个数据报。");
					// 将客户端发送的数据报发送给每一个客户端
					for(int i = 0;i < clients.size();i++){
						Client c = clients.get(i);
						dp.setSocketAddress(new InetSocketAddress(c.IP, c.udpPort)); // 此数据报发往的远程主机的 SocketAddress
						ds.send(dp);
					}
					
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
	}

}
